<template>
  <div class="am-form-group">
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-4 input-field">
      <select2
        v-model="areaData.province"
        :options="provinces"
        @input="areaData.city='';areaData.district=''"
      >
        <option value="">请选择省份</option>
      </select2>
    </div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-4  input-field">
      <select2
        :required="!!areaData.province"
        v-model="areaData.city"
        :options="cities"
        @input="areaData.district=''"
      >
        <option value="">请选择城市</option>
      </select2>
    </div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-4  input-field">
      <select2
        :required="!!areaData.province"
        v-model="areaData.district"
        :options="districts"
      >
        <option value="">请选区(县)</option>
      </select2>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      areaData: {
        province: "",
        city: localStorage.getItem("studentCity") || "",
        district: localStorage.getItem("studentDistrict") || ""
      },
      location: [],
      cityMap: {},
      districtMap: {}
    };
  },
  computed: {
    provinces: function() {
      return this.location.map(function(item) {
        return { value: item.n, text: item.n };
      });
    },
    cities: function() {
      var cities =
        this.areaData.province && this.cityMap[this.areaData.province];
      if (!cities) {
        return [];
      }
      return cities.map(function(item) {
        return { value: item.n, text: item.n };
      });
    },
    districts: function() {
      var districts =
        this.areaData.city &&
        this.districtMap[this.areaData.province + this.areaData.city];
      if (!districts) {
        return [];
      }
      return districts.map(function(item) {
        return { value: item.n, text: item.n };
      });
    }
  },

  created() {
    this.loadLocation().then(() => {
      this.areaData.province = localStorage.getItem("studentProvince") || "";
    });
  },
  methods: {
    loadLocation() {
      var _this = this;
      return new Promise((resolve, reject) => {
        $.getJSON("//static.yuyou100.com/location.json", function(ret) {
          _this.location = ret;
          for (var i = 0; i < ret.length; i++) {
            _this.cityMap[ret[i].n] = ret[i].s;
            for (var ii = 0; ii < ret[i].s.length; ii++) {
              _this.districtMap[ret[i].n + ret[i].s[ii].n] = ret[i].s[ii].s;
            }
          }
          resolve()
        });
      });
    }
  }
};
</script>
